package com.ys.store.controller;

import com.ys.store.entity.User;
import com.ys.store.service.IUserService;
import com.ys.store.service.ex.InsertException;
import com.ys.store.service.ex.UsernameDuplicatedException;
import com.ys.store.service.impl.UserServiceImpl;
import com.ys.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


// @Controller
@RestController  // @Controller + @ResponseBody
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @RequestMapping("reg")
    //   @ResponseBody // 表示此方法的响应结果以json格式进行数据响应到前端
    public JsonResult<Void> reg(User user) {
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
         User data = userService.login(username, password);
         // 向session对象中完成数据的绑定（session全局的）
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());

         return new JsonResult<User>(OK, data);
    }

    @RequestMapping("change_password")
    public JsonResult<Void> ChangePassword(String oldPassword, String newPassword, HttpSession session){
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.ChangePassword(uid, username, oldPassword, newPassword);
        return new JsonResult<>(OK);
    }





}
